<template>
	<view class="login-con">
		<view class="login-logo w100">
			<view class="fl-c mgt pdl mgl blod mgb">
				<view class="ptit mgb10">欢迎使用<text style="font-weight:600; padding-left: 8px;">张家川智慧停车</text></view>
				<view class="desctit">停车有位，出行不愁</view>
			</view>
			<view class="logo fl-cc tc mgr">
				<image style="width:90%;" src="/static/login-bg.png"></image>
			</view>
		</view>
		<view class="login-btn">
			<view class="btn-con fl-cc">
				<view class="mgb" style="width: 100%;">
					<button class="wxbtn wxbtn-green" plain open-type="getPhoneNumber" @getphonenumber="getPhoneNumber"
						style="border: none;">
						<view class="fl">
							<uni-icons type="weixin" size="18" color="#FFF"></uni-icons>
							<text class="mgl10">快捷登录</text>
						</view>
					</button>
				</view>
				<view class="mgb" style="width: 100%;">
					<view class="btn btn-primary" plain @click="onCodeLogin">
						<view class="fl">
							<view class="iconfont icon-tuichu mgr5" style="color:#f53837; font-size: 16px;"></view>
							<text>手机号登录</text>
						</view>
					</view>
				</view>
				<view class="fl mgt">我已阅读并同意<text style="color: rgba(59, 144, 253, 1);">《用户协议》</text>和<text
						style="color: rgba(59, 144, 253, 1);">《隐私协议》</text></view>
			</view>
			<view class="pdtb10 fl-cc desc">张家川欢迎您！</view>
		</view>
		<!--二次验证提醒toast-->
		<uni-toast ref="toast"></uni-toast>
		<!-- 手机验证码登录 -->
		<uni-popup ref="isCodeLoginRef" type="bottom" border-radius="10px 10px 0 0" background-color="#F7F7F7"
			:mask-click="false">
			<view style="height: 50vh;">
				<view class="fl-rsb pd">
					<view class="title">手机号登录</view>
					<uni-icons type="closeempty" size="22" color="#333" @click="closedCodeLogin"></uni-icons>
				</view>
				<view class="login-form pdlr30">
					<uni-forms :modelValue="userInfo" ref="form" :rules="rules">
						<!-- 手机号码 -->
						<uni-forms-item label="" name="phone">
							<uni-easyinput type="text" v-model="userInfo.phone"  :inputBorder="false" placeholder="请输入手机号码" :styles="loginformitem" />
						</uni-forms-item>
						<!-- 验证码 -->
						<uni-forms-item label="" name="verificationCode">
							<uni-easyinput v-model="userInfo.verificationCode"  :inputBorder="false" placeholder="请输入验证码" :styles="loginformitem" @iconClick="onClick">
								<template #right>
									<!-- uni-code ref="uCode" @change="codeChange" :seconds="seconds"
										changeText="X秒重新获取"></uni-code> -->
									<view class="scolor tag mgr pdtb blue" @click="getCode">{{codeTips}}</view>
								</template>
							</uni-easyinput>
						</uni-forms-item>
					</uni-forms>
					<view class="mgb" style="width: 100%;">
						<view class="btn btn-primary" plain @click="submit">
							<view class="fl">
								<view class="iconfont icon-tuichu mgr5" style="color:#f53837; font-size: 16px;">
								</view>
								<text>登录</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		reactive,
		ref,
		onMounted,
		nextTick,
		computed
	} from 'vue';
	// import md5 from 'blueimp-md5'; // 新增MD5库
	import router from "@/ya/router/index.js";
	import LoginApi from '@/ya/api/login.js';
	import {
		toast
	} from '@/ya/helper/index.js';
	import {
		onBackPress
	} from "@dcloudio/uni-app"
	import {
		useStore
	} from '@/ya/store';
	// 登录方式
	const uCode = ref(null);
	const loginTips = ref('底部文本提醒');
	const codeTips = ref('获取验证码');
	const seconds = ref(60);
	const isCodeLogin = ref(false);
	const isCodeLoginRef = ref();
	const isShowPwd = ref(true);
	const form = ref(null);
	const userInfo = reactive({
		phone: '',
		verificationCode: ''
	});
	const loginformitem = reactive({
		borderRadius: '5px',
		marginBottom: '30rpx',
		height: '50px !important',
		padding: '4px 8px 4px 4px',
		backgroundColor:'#FFF'
	});
	const rules = reactive({
		'tempUsername': {
			type: 'string',
			required: true,
			message: '请输入用户名',
			trigger: ['blur', 'change']
		},
		'tempPwd': {
			type: 'string',
			required: true,
			message: '请输入密码',
			trigger: ['blur', 'change']
		},
	});
	const userStore = useStore('user');
	const appConfigStore = useStore('appConfig');
	const settingConfig = computed(() => useStore('appConfig').settingConfig);
	const isEmptyStringOrNull = (value) => {
		return value === null || value === "" || value === undefined;
	}
	const loginBefore = () => {
		// 清空数据
		userStore.resetUserData();
		uni.removeStorageSync("token");
		console.log(userInfo)
		// 定义验证规则映射对象
		const validationMap1 = {
			phone: "请填写手机号码!",
			verificationCode: "请填写验证码!"
		};
		const validationMap2 = {
			code: "请填写考号/工作证号!",
			// name: "请填写姓名!",
			idCard: "请填写身份证号码!",
		};
		const validationMap = isCodeLogin.value ? validationMap1 : validationMap2;
		console.log("validationMap:", validationMap)
		const messages = [];
		// 遍历验证规则映射对象
		for (const [key, message] of Object.entries(validationMap)) {
			if (isEmptyStringOrNull(userInfo[key])) {
				messages.push(message);
			}
		}
		messages.reverse();
		console.log("message:", messages)
		if (messages.length > 0) {
			messages.forEach(item => {
				toast.value.show({
					message: item,
					type: 'error'
				});
			})
			return false
		}
		return true
	};
	// 微信小程序的“手机号快速验证”：https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/getPhoneNumber.html
	const getPhoneNumber = async (e) => {
		if (e.detail.errMsg !== 'getPhoneNumber:ok') {
			toast('快捷登录失败');
			return;
		}
		if (state.model.avatar === '') {
			toast('请获取用户头像');
			return;
		}
		if (state.model.name === '') {
			toast('请输入姓名');
			return;
		}
		state.model.phoneCode = e.detail.code;
		OperatorApi.updateOperator(state.model).then(async response => {
			if (response.code === 0) {
				// sheep.$store('user').setUserInfo(response.data);
				// await sheep.$store('user').getInfo();
				await getTabBarByUser();
				uni.redirectTo({
					url: '/pages/index'
				})
			} else {
				toast(response.msg);
			}
		});
	};
	const submit = async () => {
		console.log(router);
		router.switchTab("/pages/home/home");
		// if (!loginBefore()) {
		// 	return
		// }
		form.value.validate().then(async res => {
			// const tempType = parseInt(cUserType.value.value);
			const tempType = userInfo.tempPsw.length > 4 ? 3 : 1;
			userInfo.loginType = tempType
			console.log("登录类型:", tempType);
			switch (tempType) {
				case 3:
					userInfo.username = userInfo.tempUsername
					userInfo.password = userInfo.tempPsw
					break
				case 1:
					userInfo.code = userInfo.tempUsername
					userInfo.idCard = userInfo.tempPsw
					break
			}
			console.log("form:", userInfo);
			// 密码加密逻辑
			const encryptedInfo = {
				...userInfo,
				password: md5(userInfo.password) // 对密码进行MD5加密
			};
			// 删除多余的属性
			const tempList = {
				1: ["loginType", "code", "idCard"],
				2: ["loginType", "code", "idCard"],
				3: ["loginType", "username", "password"],
			};
			let tempUserInfo = {};
			tempList[tempType].forEach(item => {
				tempUserInfo[item] = encryptedInfo[item]
			})
			console.log("tempUserInfo:", tempUserInfo);
			await userStore.login(tempUserInfo).then(async (res) => {
				console.log("res:", res)
				if (res) {
					if (userInfo.keepPsw) {
						uni.setStorageSync('userInfo', userInfo);
					} else {
						uni.removeStorageSync("userInfo");
					}
					console.log("stor-userInfo:", uni.getStorageSync("userInfo"));
					// 动态设置底部tab
					await appConfigStore.setTabsByRole(tempType, userStore
						.userType);
					console.log("userType:", cUserType.value)
					await appConfigStore.loginAfter();
				} else {
					toast.value.show({
						message: '登录失败！用户信息或密码有误!',
						type: 'error'
					});
				}
			});
		}).catch(errors => {
			toast.value.show({
				message: '登录失败，请稍后再试；',
				type: 'error'
			});
		})
	};
	// 选择登录类型
	const onSelectedType = () => {
		// 打开登录类型选择菜单
		uni.showActionSheet({
			itemList: loginTypeList.value.map(item => item.label),
			success(res) {
				console.log(res);
				console.log(loginTypeList.value[res.tapIndex]);
				cUserType.value = loginTypeList.value[res.tapIndex];
				userInfo.loginType = cUserType.value.value;
				userInfo.typeLabel = cUserType.value.label;
			}
		});
	};
	async function getCode() {
		if (userInfo.phone == '') {
			toast.value.show({
				message: '请输入手机号码！',
				type: 'error'
			});
			return
		}
		if (uCode.value.canGetCode) {
			// 模拟向后端请求验证码
			uni.showLoading({
				title: '正在获取验证码'
			})
			uni.hideLoading();
			await LoginApi.sendSmsCode(userInfo.phone).then((res) => {
				console.log(res);
				toast.value.show({
					message: "手机验证码已发送"
				});
				uCode.value.start();
			})
		} else {
			toast.value.show({
				message: '倒计时结束后再发送'
			});
		}
	};
	const codeChange = (text) => {
		codeTips.value = text;
	};
	const onCodeLogin = () => {
		isCodeLoginRef.value.open('bottom')
	};
	const closedCodeLogin = () => {
		isCodeLoginRef.value.close();
	};
	// 自动管理
	const onAutoChange = (val) => {
		userInfo.keepPsw = val;
		uni.setStorageSync('keepPsw', userInfo.keepPsw);
	};
	let firstBackTime = 0;
	onMounted(async () => {
		// 初始化
		await nextTick();
		userInfo.keepPsw = uni.getStorageSync('keepPsw');
		uni.removeStorageSync("token");
		const tempUserInfo = uni.getStorageSync('userInfo');
		console.log('------------', tempUserInfo)
		if (userInfo.keepPsw && Object.keys(tempUserInfo).length > 0) {
			Object.keys(userInfo).forEach(key => {
				userInfo[key] = tempUserInfo[key]
			})
			// 自动登录
			submit();
		};
	});
	onBackPress(() => {
		console.log('App LastPageBackPress')
		if (firstBackTime == 0) {
			uni.showToast({
				title: '再按一次退出应用',
				position: 'bottom',
			})
			firstBackTime = Date.now()
			setTimeout(() => {
				firstBackTime = 0
			}, 2000)
			return true
		} else if (Date.now() - firstBackTime < 2000) {
			firstBackTime = Date.now()
			uni.exit()
		}
	});
</script>

<style lang="scss" scoped>
	.stext {
		padding-top: 15rpx;
	}
	.login-con {
		background-color: #FFF;
		height: 100vh;

		.login-logo {
			align-items: center;
			padding: 110px 0px 30px 0px;
			width: 100%;
			background-repeat: no-repeat;
			background-size: 90%;
			background-position: center bottom;

			.login-logo-top {
				height: 120rpx;
				width: 90%;
				font-weight: bolder;
				background-repeat: no-repeat;
				background-size: 90%;
				margin-bottom: 50rpx;
			}

			.logo {
				width: 100vw;
				height: 35vh;
				font-size: 26px;
				font-weight: bold;
			}
		}

		.login-form {}
	}

	.login-btn {
		position: absolute;
		width: 100%;
		bottom: 25px;

		.btn-con {
			padding: 0px 26px;
			margin-bottom: 30px;
		}
	}

	.login-form-item {
		border-radius: 5px;
		margin-bottom: 30rpx;
		// border: 1px solid #eee;
		padding: 4px 8px;
		background-color: rgba(25, 198, 173, 0.1);
	}

	.pdlr30 {
		padding-left: 30px;
		padding-right: 30px;
	}

	.pre-icon {
		width: 38px;
		height: 38px;
		background-color: rgba(25, 198, 173, 0.1);
		border-radius: 5px;
		display: flex;
		justify-content: center;
		align-items: center;
		margin-right: 10px;
	}

	.psubtit {
		font-size: 46rpx;
	}

	.ptit {
		font-size: 44rpx;
	}
</style>
<style>
	.uni-easyinput__content-input {
	    line-height: 45px !important;
	    height: 45px !important;
		border-radius: 10px;
	}
</style>